<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>节流、防抖</title>
  <style>
    div{
      margin-top: 10px;
      padding: 10px;
      border: 1px solid gray;
    }
    p{
      /* width: 200px; */
      height: 20px;
      border: 1px solid gray;
      opacity: .5;
      /* background-color: hotpink; */
    }
  </style>
</head>
<body>
  <div class="initial">
    <label for="initial">Initial：</label>
    <input type="text" name="initial" class="input">
    <button>Clear</button>
    <p class="initial_text"></p>
  </div>
  <div class="throttle">
    <label for="throttle">Throttle：</label>
    <!-- <input type="text" name="throttle" class="throttle_input"> -->
    <p class="throttle_text"></p>
  </div>
  <div class="de_bounce">
    <label for="deBounce">DeBpunce：</label>
    <!-- <input type="text" name="deBounce" class="de_bounce_input"> -->
    <p class="de_bounce_text"></p>
  </div>
</body>
<script>
  //初始
  const inp = document.getElementsByClassName("input")[0];
  const initialInputText = document.getElementsByClassName("initial_text")[0];
  inp.addEventListener('input', (e)=>{
    console.log('inputValue1:', e.target.value);
    initialInputText.innerText = e.target.value;
  })

  //节流：在wait时间内最多执行一次目标function
  const throttleText = document.getElementsByClassName("throttle_text")[0];
  function throttle(fun, delay = 500) {
    let timer;
    return function() {
      let that = this;
      let _args = arguments;
      if (!timer) {  //如果定时器不存在,则设置新的定时器,到时后,才执行回调,并将定时器设为null
        timer = setTimeout(function(){
            timer = null;
            fun.apply(that, _args)
        }, delay)
      }
    }
  }
  //定义赋值函数
  function assignment (content) {
    console.log('throttleValue2:', content)
    throttleText.innerText = content
  }
  //绑定节流
  let throttleEvent = throttle(assignment, 1000)
  //监听触发节流
  inp.addEventListener('input', (e)=>{
    throttleEvent(e.target.value)
  })

  //防抖：延迟wait时间后执行目标function
  const deBpunceText = document.getElementsByClassName("de_bounce_text")[0];
  inp.addEventListener('input', (e)=>{
    let deBounce = setTimeout(()=>{
      console.log('deBounceValue3:', e.target.value)
      deBpunceText.innerText = e.target.value
    },1000)
  })

  //重置input
  const clearBtn = document.getElementsByTagName("button")[0]
  clearBtn.onclick = () => {
    inp.value = ''
  }

  //相关方案
  //lodash节流：https://www.lodashjs.com/docs/lodash.throttle
  //lodash防抖：https://www.lodashjs.com/docs/lodash.debounce
</script>
</html>